﻿using System;
using System.Collections.Generic;
using ICSharpCode.Core;
using ICSharpCode.Core.Services;
using System.IO
;
using System.Windows;

namespace Agnes.Core
{
    /// <summary>
    /// 系统即将关闭事件
    /// </summary>
    public delegate void ShutDown();

    /// <summary>
    /// 初始化完毕事件
    /// </summary>
    public delegate void InitFinished();

    /// <summary>
    /// Agnes 平台基础服务
    /// </summary>
    public class AgnesServiceManager
    {
        #region 各种服务

        private static AgnesWorkBenchService _agnesWorkBenchService = null;
        /// <summary>
        /// Agnes工作区服务
        /// </summary>
        public static AgnesWorkBenchService AgnesWorkBenchService
        {
            get
            {
                if (_agnesWorkBenchService == null)
                {
                    LogServ.Info("启动工作区服务");
                    _agnesWorkBenchService = new AgnesWorkBenchService();
                }
                return _agnesWorkBenchService;
            }
        }

        private static AgnesSlnService _agnesSlnService = null;
        /// <summary>
        /// 解决方案服务
        /// </summary>
        public static AgnesSlnService AgnesSlnService
        {
            get
            {
                if (_agnesSlnService == null)
                {
                    LogServ.Info("启动解决方案服务");
                    _agnesSlnService = new AgnesSlnService();
                }
                return _agnesSlnService;
            }
        }

        #endregion

        #region 私有变量

        private List<string> addInFiles = new List<string>();
        private List<string> disabledAddIns = new List<string>();

        #endregion

        #region 私有成员

        /// <summary>
        /// 初始化Agnes核心服务组
        /// </summary>
        private void StartCoreSerivce()
        {
            //日志服务
            LogServ = new log4netLoggingService();
            LogServ.Info("日志服务已启动");
            LogServ.Info("加载系统环境变量 ");

            //路径服务
            InitPath();

            //属性服务
            LogServ.Info("启动属性服务");
            PropertyService.InitializeService(PropertyPath, "Properties");
            PropertyService.Load();

            //插件服务
            InitAddIns();

            //资源服务
            //InitResourceService();

            //WPF命令服务
            AgnesCommandService.InitCommandService();

        }

        private void InitPath()
        {
            RootPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..");
            AddInPath = Path.Combine(RootPath, "AddIns");
            DataPath = Path.Combine(RootPath, "Data");
            PropertyPath = Path.Combine(DataPath, "GobalConfig\\AgnesProperties.xml");
        }

        private void InitAddIns()
        {
            LogServ.Info("搜索插件 ... ...");
            if (AddInPath == null)
            {
                throw new ArgumentNullException("addInDir");
            }
            addInFiles.AddRange(Directory.GetFiles(AddInPath, "*.addin", SearchOption.AllDirectories));
            LogServ.Info("已经找到了 " + addInFiles.Count + " 个插件配置");
            //加载插件
            LogServ.Info("加载插件树");
            AddInTree.Load(addInFiles, disabledAddIns);
        }

        private void InitResourceService()
        {
            LogServ.Info("Initialize Resources Services... ...");
            ResourceService.InitializeService(Path.Combine(DataPath, "Resources"));
            StringParser.RegisterStringTagProvider(new AppNameProvider { appName = "Agnes" });
        }

        #endregion

        #region 单例

        private AgnesServiceManager()
        {
        }

        private static AgnesServiceManager _instance = null;

        public static AgnesServiceManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new AgnesServiceManager();
                    _instance.StartCoreSerivce();
                }
                return _instance;
            }
        }

        #endregion

        #region 属性

        /// <summary>
        /// 系统关闭事件
        /// </summary>
        public event ShutDown ShutdownEventHandler;

        /// <summary>
        /// 系统初始化完毕界面
        /// </summary>
        public event InitFinished InitFinishedHandler;

        /// <summary>
        /// Log Service 
        /// Default: log4net Logging Service
        /// </summary>
        public static ILoggingService LogServ { get; private set; }

        /// <summary>
        /// 软件的安装目录
        /// </summary>
        public static string RootPath { get; private set; }

        /// <summary>
        /// 插件文件夹路径
        /// </summary>
        public static string AddInPath { get; private set; }

        /// <summary>
        /// 数据文件夹路径
        /// </summary>
        public static string DataPath { get; private set; }

        /// <summary>
        /// 配置文件夹的路径
        /// </summary>
        public static string PropertyPath { get; private set; }

        #endregion

        /// <summary>
        /// Add the specified .addin file to the list of AddIn files to load.
        /// </summary>
        public void AddAddInFile(string addInFile)
        {
            if (addInFile == null)
            {
                throw new ArgumentNullException("addInFile");
            }
            addInFiles.Add(addInFile);
        }

        /// <summary>
        /// 执行挂接在/Workspace/Launch的Command.Run();
        /// </summary>
        public void StartLaunchCodon()
        {
            // run workspace autostart commands
            LogServ.Info("加载启动插件 ... ...");
            string addName = "";
            try
            {
                foreach (LaunchDiscriptor i in AddInTree.BuildItems<LaunchDiscriptor>("Agnes/Launch", null, false))
                {
                    addName = i.Codon.AddIn.Name;
                    (i.Codon.AddIn.CreateObject(i.Codon.Properties["class"]) as ICommand).Run();
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("加载插件出现严重异常！需要关闭......");
                LogServ.ErrorFormatted("加载插件 " + addName + " 失败！原因:" + ex.Message);
            }
        }

        /// <summary>
        /// 系统关闭动作
        /// </summary>
        public void OnShutDown()
        {
            LogServ.Info("保存属性配置... ...");
            PropertyService.Save();

            LogServ.Info("系统正在关闭... ...");
            if (ShutdownEventHandler != null)
            {
                ShutdownEventHandler();
            }
        }

        /// <summary>
        /// 系统初始化完毕动作
        /// </summary>
        public void OnInitFinished()
        {
            LogServ.Info("系统初始化完毕");
            if (InitFinishedHandler != null)
            {
                InitFinishedHandler();
            }
        }
    }

    sealed class AppNameProvider : IStringTagProvider
    {
        internal string appName;

        public string ProvideString(string tag, StringTagPair[] customTags)
        {
            if (string.Equals(tag, "AppName", StringComparison.OrdinalIgnoreCase))
                return appName;
            else
                return null;
        }
    }
}
